package ch.electronet.wjw.index;

import java.util.LinkedHashSet;
import java.util.Set;

public class SearchVisitor<T> implements NodeVisitor {

	private final Set<T> results;
	private String query = null;

	public void visit(Node node) {
		int key = -1;
		if (query.length() > 0)
			key = query.charAt(0);
		if (key != -1 && key != '*') {
			Node child = node.getChild(key);
			if (child != null) {
				query = query.substring(1);
				child.accept(this);
			}
		} else if (key == '*') {
			results.addAll(node.getData());
			for (Node child : node.getChildren()) {
				child.accept(this);
			}
		} else if (key == -1) {
			results.addAll(node.getData());
			query = null;
		}
	}

	public SearchVisitor(String query, Analyzer analyzer) {
		if (analyzer != null)
			this.query = analyzer.analyze(query);
		else
			this.query = query;

		this.results = new LinkedHashSet<T>();
	}

	public Set<T> getResult() {
		return results;
	}

}
